<template>
    <div>
        <div class="w-form-header">
            <!-- {{ type == "create" ? "添加项目" : "修改项目" }} -->
            <div>
                <el-button type="success" @click="save" :loading="saveLoading"
                    >保存</el-button
                >
                <!-- <el-button type="primary" plain round @click="resetForm">重置</el-button> -->
            </div>
        </div>
        <div class="gva-form-box admin-content">
            <div class="form-box w-form-box">
                <el-form
                    :model="formData"
                    ref="elFormRef"
                    label-position="right"
                    :rules="rule"
                    label-width="120px"
                >
                    <el-form-item
                        :label="`${il8n('xiangmubianhao.label')}:`"
                        prop="projectNum"
                    >
                        <el-input
                            v-model="formData.projectNum"
                            :clearable="true"
                            :placeholder="`${il8n(
                                'xiangmubianhao.placeholder1'
                            )}`"
                            disabled
                        />
                    </el-form-item>
                    <el-form-item
                        :label="`${il8n('SBU.label')}:`"
                        prop="sbuName"
                    >
                        <el-select
                            v-model="formData.sbuName"
                            :placeholder="`${il8n('SBU.placeholder')}`"
                            style="width: 100%"
                            :clearable="true"
                            filterable
                            remote
                            :remote-method="getSbuData"
                            @change="sbuChange"
                        >
                            <el-option
                                v-for="(item, key) in sbuOptions"
                                :key="key"
                                :label="item.sbuName"
                                :value="item.sbuName"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        :label="`${il8n('kehubianhao.label')}:`"
                        prop="customerName"
                    >
                        <el-select
                            v-model="formData.customerName"
                            :placeholder="`${il8n('kehubianhao.placeholder')}`"
                            style="width: 100%"
                            filterable
                            @focus="customerFocur"
                            @change="customerChange"
                        >
                            <el-option
                                v-for="(item, key) in customerOptions"
                                :key="key"
                                :label="item.customerNum"
                                :value="item.customerNum"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item
                        :label="`${il8n('pinpai.label')}:`"
                        prop="brandName"
                    >
                        <el-select
                            v-model="formData.brandName"
                            :placeholder="`${il8n('pinpai.placeholder')}`"
                            style="width: 100%"
                            :clearable="true"
                            filterable
                            @focus="brandFocur"
                        >
                            <el-option
                                v-for="(item, key) in brandOptions"
                                :key="key"
                                :label="item.brandName"
                                :value="item.brandName"
                            />
                        </el-select>
                    </el-form-item>
                    <!-- <el-form-item
                        :label="`${il8n('chuangjiankuanshishuliang.label')}:`"
                        prop="createStyleAmount"
                    >
                        <el-input
                            v-model.number="formData.createStyleAmount"
                            :clearable="true"
                            :placeholder="`${il8n(
                                'chuangjiankuanshishuliang.placeholder'
                            )}`"
                        />
                    </el-form-item> -->
                    <!-- <div class="form-footer">
                        <el-button
                            type="primary"
                            @click="save"
                            :loading="saveLoading"
                            >保存</el-button
                        >
                        <el-button type="primary" @click="back">取消</el-button>
                    </div> -->
                </el-form>
            </div>
        </div>
    </div>
</template>

<script setup>
import {
    createSbuProjects,
    updateSbuProjects,
    findSbuProjects,
} from "@/api/plmSbuProjects";
import { getCustomerInfoList, findCustomerInfo } from "@/api/confCustomerInfo";
import { getSbuDataList } from "@/api/confSbuData";
import { getBrandDataList } from "@/api/confBrandData";

defineOptions({
    name: "SbuProjectsFormAdd",
});

// 自动获取字典
import { getDictFunc } from "@/utils/format";
import { emitter } from "@/utils/bus.js";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { ref, reactive, onMounted } from "vue";
import { useI18n } from "vue-i18n";

const { t: il8n } = useI18n();

const route = useRoute();
const router = useRouter();

const type = ref("");
const sbuTypesOptions = ref([]);
const loading = ref(false);
const sbuOptions = ref([]); // sbu列表
const customerOptions = ref([]); // 客户编号列表
const brandOptions = ref([]); // 品牌列表
const saveLoading = ref(false); // 保存状态
const formData = ref({
    sbuName: "",
    customerName: "",
    brandName: "",
});
// 验证规则
const rule = ref({
    sbuName: [{ required: true, message: "请选择SBU", trigger: "change" }],
    customerName: [
        { required: true, message: "请选择客户编号", trigger: "change" },
    ],
    brandName: [{ required: true, message: "请选择品牌", trigger: "change" }],
    createStyleAmount: [{ type: "number", message: "请输入数字" }],
});

const elFormRef = ref();

// 初始化方法
const init = async () => {
    // 建议通过url传参获取目标数据ID 调用 find方法进行查询数据操作 从而决定本页面是create还是update 以下为id作为url参数示例
    if (route.query.id) {
        const res = await findSbuProjects({ ID: route.query.id });
        if (res.code === 0) {
            formData.value = res.data.resbuProjects;
            type.value = "update";
        }
    } else {
        type.value = "create";
    }
};

init();
function resetForm() {
    elFormRef.value.resetFields();
}
// 保存按钮
const save = async () => {
    elFormRef.value?.validate(async (valid) => {
        if (!valid) return;
        let res;
        saveLoading.value = true;
        formData.value['createStyleAmount'] = +formData.value['createStyleAmount']
        switch (type.value) {
            case "create":
                res = await createSbuProjects(formData.value);

                break;
            case "update":
                res = await updateSbuProjects(formData.value);
                break;
            default:
                res = await createSbuProjects(formData.value);
                break;
        }
        
        saveLoading.value = false;
        if (res.code !== 0) {
            return;
        }
        ElMessage({
            type: "success",
            message: type == "create" ? "创建成功" : "更改成功",
        });
        elFormRef.value.resetFields();
        emitter.emit("closeThisPage", { path: "/layout/plmSbuProjectsView",
            query:{
                id: res.data.ID,
                action:'v',
                subTitle:res.data.projectNum
            }
         });
    });
};

// 返回按钮
const back = () => {
    emitter.emit("closeThisPage");
    return;
    router.go(-1);
};

// 获取sbu列表
const getSbuData = async (keyword) => {
    await getSbuDataList({ page: 1, pageSize: 100, sbuName: keyword }).then(
        (res) => {
            if (res.code === 0) {
                sbuOptions.value = res.data.list;
            }
        }
    );
};

// 获取品牌列表
const getBrandData = async (keyword) => {
    await findCustomerInfo({ customerNum: keyword }).then((res) => {
        if (res.code === 0) {
            brandOptions.value = res.data.recustomerInfo.brandDatas;
        }
    });
};

// select的sbu改变sbuChange
const sbuChange = () => {
    let index = sbuOptions.value.findIndex((item) => {
        return item.sbuName == formData.value.sbuName;
    });
    formData.value.customerName = "";
    formData.value.brandName = "";
    customerOptions.value = sbuOptions.value[index].customerNum
        .split(",")
        .map((res) => {
            return { customerNum: res };
        });
    brandOptions.value = [];
};

// select搜索客户编号列表
const customerFocur = async (query) => {
    if (!formData.value.sbuName) {
        ElMessage({
            type: "warning",
            message: "请先选择sbu",
        });
        return;
    }
};

// 客户编号改变
const customerChange = () => {
    let index = customerOptions.value.findIndex((item) => {
        return item.customerNum == formData.value.customerName;
    });
    if(formData.value.customerName == 'INHSE'){
        if(rule.value.brandName) delete rule.value.brandName
    }else{
        rule.value['brandName'] = [{ required: true, message: "请选择品牌", trigger: "change" }]
    }
    formData.value.brandName = "";
    // 获取品牌列表
    brandOptions.value = [];
    getBrandData(customerOptions.value[index].customerNum);
};

// select搜索品牌列表
const brandFocur = async (query) => {
    if (!formData.value.customerName) {
        ElMessage({
            type: "warning",
            message: "请先选客户",
        });
        return;
    }
    // console.log("搜索", query);
    // getBrandData(query);
};

onMounted(() => {
    getSbuData();
});
</script>

<style lang="scss" scoped>
@import url("@/style/common/common.scss");
.form-box {
    width: 45%;
    margin: 0 auto;
}
.form-footer {
    text-align: center;
}
</style>
